﻿using System;

namespace rpcdump
{
    class Program
    {
        static bool bExit = false;
        static void Main(string[] args)
        {
            Console.WriteLine("start to dump");
            System.Threading.ThreadPool.QueueUserWorkItem(
                (a) =>
                {
                    DumpThread();
                });

            while (bExit == false)
            {
                var line = Console.ReadLine();
            }
        }
        static System.Net.WebClient wc = new System.Net.WebClient();
        static int GetCount()
        {
            var getcounturl = "http://127.0.0.1:20332/?jsonrpc=2.0&id=1&method=getblockcount&params=[]";
            var info = wc.DownloadString(getcounturl);
            var json = Newtonsoft.Json.Linq.JObject.Parse(info);
            int count = (int)json["result"];
            return count;
        }
        static string GetBlock(int block)
        {
            var getcounturl = "http://127.0.0.1:20332/?jsonrpc=2.0&id=1&method=getblock&params=[" + block + ",1]";
            var info = wc.DownloadString(getcounturl);
            var json = Newtonsoft.Json.Linq.JObject.Parse(info);
            var bb = json["result"].ToString();
            return bb;

        }
        static void DumpThread()
        {
            if(System.IO.Directory.Exists("dumpdata")==false)
            {
                System.IO.Directory.CreateDirectory("dumpdata");
            }
            int bcount = GetCount();
            for (var i = 0; i < Math.Min(bcount, 100000); i++)
            {
                var bstr = GetBlock(i);
                var path = "dumpdata" + System.IO.Path.DirectorySeparatorChar + i.ToString("D08") + ".txt";
                System.IO.File.Delete(path);
                System.IO.File.WriteAllText(path, bstr, System.Text.Encoding.UTF8);
                if(i%1000==0)
                {
                    Console.WriteLine("dump =" + i);
                }
            }
            bExit = true;
        }
    }
}
